package org.npu.controller;

import org.apache.ibatis.session.SqlSession;
import org.npu.dao.UserDao;
import org.npu.entity.User;
import org.npu.util.MyBatisUtils;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html; charset=utf-8");

        String nameCheck = req.getParameter("username");
        String passwordCheck = req.getParameter("password");

        //获取操作数据库的对象
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        UserDao dao = sqlSession.getMapper(UserDao.class);

        int result = dao.Login(nameCheck, passwordCheck);

        if (result == 1) {
            //登录成功
            System.out.println("login successfully!");

            User curUser = dao.queryByName(nameCheck);//当前用户信息存储到session
            req.getSession().setAttribute("curUser", curUser);

            //添加cookie
            Cookie username = new Cookie("username", nameCheck);
            Cookie password = new Cookie("password", passwordCheck);
            resp.addCookie(username);
            resp.addCookie(password);

            // 在login页面中弹窗”登陆成功“
            resp.setContentType("text/html");
            resp.getWriter().println("<!DOCTYPE html>" +
                    "<html lang='zh'>" +
                    "<head>" +
                    "<meta charset=UTF-8>" +
                    "<meta http-equiv='refresh' content='0; url=/bigweb/home'/>" +
                    "</head>" +
                    "<body>" +
                    "<script>alert('登陆成功!欢迎用户：" + nameCheck + "');</script>" +
                    "</body>" +
                    "</html>"
            );
            // resp.sendRedirect("/bigweb/home");
        } else {
            //登录失败
            System.out.println("login failed!");
            //到时候写一个登录错误界面
            // 在login页面中弹窗 ”登陆失败“ 并重定向到登录页面
            resp.setContentType("text/html");
            resp.getWriter().println("<!DOCTYPE html>" +
                    "<html lang='zh'>" +
                    "<head>" +
                    "<meta charset=UTF-8>" +
                    "<meta http-equiv='refresh' content='0; url=/bigweb/loginpage'/>" +
                    "</head>" +
                    "<body>" +
                    "<script>alert('登陆失败!');</script>" +
                    "</body>" +
                    "</html>"
            );
        }
    }
}
